package com.example.myapplication

import android.app.DatePickerDialog
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*
import com.example.myapplication.utils.PermissionHelper

class AddPatientActivity : AppCompatActivity() {
    
    private lateinit var editTextName: EditText
    private lateinit var editTextAge: EditText
    private lateinit var spinnerGender: android.widget.Spinner
    private lateinit var editTextExaminationDate: EditText
    private lateinit var editTextAdmissionDate: EditText
    private lateinit var editTextReporter: EditText
    private lateinit var editTextExaminationName: EditText
    private lateinit var editTextDepartment: EditText
    private lateinit var editTextDiagnosis: EditText
    private lateinit var editTextDoctor: EditText
    private lateinit var editTextPhone: EditText
    private lateinit var editTextNotes: EditText
    private lateinit var buttonSave: Button
    private lateinit var buttonCancel: Button
    private lateinit var databaseHelper: DatabaseHelper
    
    private var selectedDate: Date = Date()
    private var selectedAdmissionDate: Date = Date()
    private val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault())
    private val genderList = listOf("男", "女", "其他")
    private var isEditMode = false
    private var editingPatientId: Long? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("AddPatientActivity", "onCreate开始")
        
        try {
            setContentView(R.layout.activity_add_patient)
            Log.d("AddPatientActivity", "布局设置成功")
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "设置布局失败", e)
            Toast.makeText(this, "布局加载失败: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
            return
        }
        
        // 添加全局异常处理
        Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
            Log.e("AddPatientActivity", "未捕获异常: ${throwable.message}", throwable)
        }
        
        // 设置软输入模式，确保键盘弹出时布局能够调整
        window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        
        // 检查用户是否已登录 - 移到权限检查之前
        if (UserSession.currentUser == null) {
            Log.e("AddPatientActivity", "用户未登录")
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        // 检查存储权限 - 对于Android 12，存储权限可能不是必需的
        try {
            if (!PermissionHelper.checkStoragePermission(this)) {
                // 对于Android 12+，尝试请求权限但不强制退出
                PermissionHelper.requestStoragePermission(this)
                Log.w("AddPatientActivity", "存储权限未授予，但继续执行")
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "权限检查失败", e)
            // 权限检查失败不阻止应用继续运行
        }
        
        try {
            databaseHelper = DatabaseHelper(this)
            Log.d("AddPatientActivity", "数据库助手初始化成功")
            
            // 测试数据库连接
            if (!databaseHelper.isDatabaseAvailable()) {
                Log.e("AddPatientActivity", "数据库连接测试失败")
                Toast.makeText(this, "数据库连接失败，请重启应用", Toast.LENGTH_LONG).show()
                finish()
                return
            }
            Log.d("AddPatientActivity", "数据库连接测试成功")
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "数据库助手初始化失败", e)
            Toast.makeText(this, "数据库初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
            return
        }
        
        try {
            initViews()
            Log.d("AddPatientActivity", "视图初始化成功")
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "视图初始化失败", e)
            Toast.makeText(this, "视图初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
            return
        }
        
        try {
            setupListeners()
            Log.d("AddPatientActivity", "监听器设置成功")
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "监听器设置失败", e)
            Toast.makeText(this, "监听器设置失败: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
            return
        }
        
        // 判断是否为编辑模式
        try {
            val editPatient = intent.getSerializableExtra("edit_patient") as? Patient
            if (editPatient != null) {
                isEditMode = true
                editingPatientId = editPatient.id
                fillPatientData(editPatient)
                buttonSave.text = "保存修改"
                title = "编辑患者信息"
                Log.d("AddPatientActivity", "编辑模式设置成功")
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "编辑模式设置失败", e)
        }
        
        Toast.makeText(this, if (isEditMode) "编辑患者页面加载成功！" else "添加患者页面加载成功！", Toast.LENGTH_SHORT).show()
        Log.d("AddPatientActivity", "onCreate完成")
    }
    
    private fun initViews() {
        Log.d("AddPatientActivity", "开始初始化视图")
        
        try {
        editTextName = findViewById(R.id.editTextName)
        spinnerGender = findViewById(R.id.spinnerGender)
        editTextExaminationDate = findViewById(R.id.editTextExaminationDate)
        editTextAdmissionDate = findViewById(R.id.editTextAdmissionDate)
        editTextReporter = findViewById(R.id.editTextReporter)
        editTextExaminationName = findViewById(R.id.editTextExaminationName)
        editTextDepartment = findViewById(R.id.editTextDepartment)
        editTextDiagnosis = findViewById(R.id.editTextDiagnosis)
        editTextNotes = findViewById(R.id.editTextNotes)
        buttonSave = findViewById(R.id.buttonSave)
        buttonCancel = findViewById(R.id.buttonCancel)
        
        Log.d("AddPatientActivity", "所有视图组件找到成功")
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "视图组件查找失败", e)
            throw e
        }
        
        // 性别下拉
        try {
        val genderAdapter = android.widget.ArrayAdapter(this, android.R.layout.simple_spinner_item, genderList)
        genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerGender.adapter = genderAdapter
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "性别下拉设置失败", e)
        }
        
        // 设置当前日期为默认值
        try {
        editTextExaminationDate.setText(dateFormat.format(selectedDate))
        editTextAdmissionDate.setText(dateFormat.format(selectedAdmissionDate))
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "默认日期设置失败", e)
        }
        
        // 设置默认汇报人为当前用户的真实姓名
        try {
        val currentUser = UserSession.currentUser
        if (currentUser != null) {
            editTextReporter.setText(currentUser.realName)
            editTextDepartment.setText(currentUser.department)
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "默认用户信息设置失败", e)
        }
        
        Log.d("AddPatientActivity", "视图初始化完成")
    }
    
    private fun setupListeners() {
        try {
        editTextExaminationDate.setOnClickListener {
            showDatePicker(editTextExaminationDate, true)
        }
        editTextAdmissionDate.setOnClickListener {
            showDatePicker(editTextAdmissionDate, false)
        }
        buttonSave.setOnClickListener {
            savePatient()
        }
        buttonCancel.setOnClickListener {
            finish()
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "监听器设置失败", e)
            throw e
        }
    }
    
    private fun showDatePicker(editText: EditText, isExamination: Boolean) {
        try {
        val calendar = Calendar.getInstance().apply {
            time = if (isExamination) selectedDate else selectedAdmissionDate
        }
        val datePickerDialog = android.app.DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                    try {
                calendar.set(year, month, dayOfMonth)
                val pickedDate = calendar.time
                if (isExamination) {
                    selectedDate = pickedDate
                } else {
                    selectedAdmissionDate = pickedDate
                }
                editText.setText(dateFormat.format(pickedDate))
                    } catch (e: Exception) {
                        Log.e("AddPatientActivity", "日期选择处理失败", e)
                        Toast.makeText(this, "日期设置失败", Toast.LENGTH_SHORT).show()
                    }
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
        datePickerDialog.show()
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "日期选择器显示失败", e)
            Toast.makeText(this, "日期选择器启动失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun fillPatientData(patient: Patient) {
        try {
        editTextName.setText(patient.name)
        spinnerGender.setSelection(genderList.indexOf(patient.gender).coerceAtLeast(0))
        editTextExaminationDate.setText(dateFormat.format(patient.examinationDate))
        editTextAdmissionDate.setText(patient.admissionDate)
        editTextReporter.setText(patient.reporter)
        editTextExaminationName.setText(patient.examinationName)
        editTextDepartment.setText(patient.department)
        editTextDiagnosis.setText(patient.diagnosis)
        editTextNotes.setText(patient.notes)
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "填充患者数据失败", e)
            Toast.makeText(this, "数据填充失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun savePatient() {
                 try {
             Log.d("AddPatientActivity", "开始保存患者信息")
        val name = editTextName.text.toString().trim()
        val gender = spinnerGender.selectedItem?.toString() ?: ""
        val examinationDateStr = editTextExaminationDate.text.toString().trim()
        val admissionDateStr = editTextAdmissionDate.text.toString().trim()
        val reporter = editTextReporter.text.toString().trim()
        val examinationName = editTextExaminationName.text.toString().trim()
        val department = editTextDepartment.text.toString().trim()
        val diagnosis = editTextDiagnosis.text.toString().trim()
        val notes = editTextNotes.text.toString().trim()
        
        Log.d("AddPatientActivity", "表单数据: name=$name, gender=$gender, examinationDate=$examinationDateStr, admissionDate=$admissionDateStr, reporter=$reporter, examinationName=$examinationName, department=$department")
            
        // 校验
        if (name.isEmpty() || gender.isEmpty() || examinationDateStr.isEmpty() || admissionDateStr.isEmpty() || reporter.isEmpty() || examinationName.isEmpty() || department.isEmpty()) {
                Toast.makeText(this, getString(R.string.please_fill_all_fields), Toast.LENGTH_SHORT).show()
                return
        }
            
        // 日期格式校验
            val examinationDate = try { 
                dateFormat.parse(examinationDateStr) 
            } catch (e: Exception) { 
                Log.e("AddPatientActivity", "检查日期解析失败", e)
                null 
            }
            val admissionDate = try { 
                dateFormat.parse(admissionDateStr) 
            } catch (e: Exception) { 
                Log.e("AddPatientActivity", "入院日期解析失败", e)
                null 
            }
            
        if (examinationDate == null || admissionDate == null) {
                Toast.makeText(this, "日期格式错误", Toast.LENGTH_SHORT).show()
                return
        }
            
        val currentUser = UserSession.currentUser
        if (currentUser == null) {
                Toast.makeText(this, "用户信息错误", Toast.LENGTH_SHORT).show()
                return
        }

        val patientId: Long = editingPatientId ?: 0L
        val patient = Patient(
            id = patientId,
            name = name,
            gender = gender,
            examinationDate = examinationDate,
            admissionDate = admissionDateStr,
            diagnosis = diagnosis,
            notes = notes,
            reporter = reporter,
            examinationName = examinationName,
            department = department,
            reportedBy = currentUser.id,
            reportedByType = currentUser.userType,
            reportTime = Date()
        )
            
        val result: Int = if (isEditMode) {
                 databaseHelper.updatePatientSafely(patient)
        } else {
                 databaseHelper.addPatientSafely(patient).toInt()
        }
            
        if (result > 0) {
            // 发送实时消息通知
            if (!isEditMode) {
                    try {
                sendRealtimeNotification(patient)
                    } catch (e: Exception) {
                        Log.e("AddPatientActivity", "实时消息发送失败", e)
                        // 实时消息发送失败不影响保存操作
                    }
            }
            
            Toast.makeText(this, if (isEditMode) "患者信息修改成功" else "患者信息添加成功", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            Toast.makeText(this, if (isEditMode) "修改失败" else "添加失败", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "保存患者信息失败", e)
            Toast.makeText(this, "保存失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    /**
     * 发送实时消息通知
     */
    private fun sendRealtimeNotification(patient: Patient) {
        try {
            // 通过WebSocket发送实时消息（可选功能）
            val webSocketManager = com.example.myapplication.realtime.WebSocketManager.getInstance(this)
            if (webSocketManager.isConnected()) {
            webSocketManager.sendPatientReport(
                patientId = patient.id,
                patientName = patient.name,
                reporterName = patient.reporter,
                department = patient.department
            )
            Log.d("AddPatientActivity", "实时消息发送成功")
            } else {
                Log.w("AddPatientActivity", "WebSocket未连接，跳过实时消息发送")
                // 不显示错误提示，因为这是可选功能
            }
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "实时消息发送失败", e)
            // 不抛出异常，避免影响主要功能
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        try {
            databaseHelper.close()
        } catch (e: Exception) {
            Log.e("AddPatientActivity", "数据库关闭失败", e)
        }
    }
} 